package ningbo.IO;

import java.io.*;
import java.util.Scanner;


/**
 * @Author 宁铂
 * @Date 2021/7/27 14:32
 * @Version 1.0
 */
public class TestCopyFile {
    /** 通过流完成文件复制的操作 */
    public static void main(String[] args) {
        //提示并接收用户输入的源文件路径与目标路径
        System.out.println("请输入您要复制的源文件路径:");
        String f = new Scanner(System.in).nextLine();

        System.out.println("请输入您目标文件的路径");
        String t = new Scanner(System.in).nextLine();

        ZFCopy(f,t);  /** 使用字节流 */
        //ZJCopy(f,t);  /** 使用字符流 */
    }

    private static void ZJCopy(String f, String t) {
        InputStream in = null;
        OutputStream out = null;

        try {
            in = new BufferedInputStream(new FileInputStream(f));
            out = new BufferedOutputStream(new FileOutputStream(t));

            int b;
            while ((b = in.read()) != -1){
                out.write(b);
            }
            System.out.println("文件复制成功");
        } catch (Exception e) {
            System.out.println("文件复制失败");
            e.printStackTrace();
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void ZFCopy(String f, String t) {
        Reader in = null;
        Writer out = null;

        try {
            in = new BufferedReader(new FileReader(f));
            out = new BufferedWriter(new FileWriter(t));

            int b;
            while((b = in.read()) != -1){
                /** 把读取到的内容复制到文件中 */
                out.write(b);
            }

            System.out.println("文件复制成功");
        } catch (Exception e) {
            System.out.println("文件复制失败");
            e.printStackTrace();
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
